package cn.okcode.slowjson.internal;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.OpenOption;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author pyk13
 */
public class FileUtils {

    public static String loadString(String fileName) {
        return loadString(fileName, StandardCharsets.UTF_8);
    }

    public static String loadString(String fileName, Charset charset) {
        StringBuilder out = new StringBuilder();
        int i = 0;
        for (String string : loadLines(fileName, charset)) {
            if (i > 0) {
                out.append(System.lineSeparator());
            }
            i++;
            out.append(string);
        }
        return out.toString();
    }

    public static List<String> loadLines(InputStream inputStream) {
        return new BufferedReader(new InputStreamReader(inputStream))
                .lines().collect(Collectors.toList());
    }

    public static List<String> loadLines(String fileName) {
        return loadLines(fileName, StandardCharsets.UTF_8);
    }

    public static List<String> loadLines(String fileName, Charset charset) {
        try (Stream<String> stream = Files.lines(Paths.get(fileName), charset)) {
            return stream.collect(Collectors.toList());
        } catch (IOException e) {
            throw new RuntimeException("读取文件出错,路径：" + fileName, e);
        }
    }

    public static void saveString(String fileName, String string, OpenOption option) {
        try {
            Files.write(Paths.get(fileName), string.getBytes(StandardCharsets.UTF_8), option);
        } catch (IOException e) {
            throw new RuntimeException("写入文件出错,路径：" + fileName, e);
        }
    }

    public static void truncateSaveString(String fileName, String string) {
        saveString(fileName, string, StandardOpenOption.TRUNCATE_EXISTING);
    }

    public static void appendSaveString(String fileName, String string) {
        saveString(fileName, string, StandardOpenOption.APPEND);
    }

    public static void createSaveString(String fileName, String string) {
        saveString(fileName, string, StandardOpenOption.CREATE);
    }

    public static void createNewSaveString(String fileName, String string) {
        saveString(fileName, string, StandardOpenOption.CREATE_NEW);
    }
}
